/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.p2psimulator.entity.overlaynetwork.structures;

import org.p2psimulator.entity.Id;
import org.p2psimulator.entity.id.DoubleId;
import org.p2psimulator.util.Tuple;

/**
 *
 * @author Amorim
 */
public class ChordFingerRing extends Ring<Id> {

    public ChordFingerRing(int M) {
        super(M);
    }

    @Override
    public void insertNode(Id<Double> key, Id value) {
        vector.add(0,key);
        if (!ring.isEmpty()) {
            for (int i = 0; i < ring.size(); i++) {

                if (key.getValue() == ring.get(i).getA().getValue()) {
                    return;
                } else if (key.getValue() < ring.get(i).getA().getValue()) {

                    Tuple<Id<Double>, Id> tuple = new Tuple<Id<Double>, Id>(
                            key, value);
                    ring.add(i, tuple);
                    
                    return;
                }
            }
        }
        ring.add(new Tuple<Id<Double>, Id>(
                key, value));
        return;
    }

    public boolean contains(Id key) {
        for (Tuple<Id<Double>, Id> t : ring) {
            if (t.getA().isEqual(key)) {
                return true;
            }
        }
        return false;

    }

    public boolean remove(Id key) {
        Tuple<Id<Double>, Id> r = null;
        for (Tuple<Id<Double>, Id> t : ring) {
            if (t.getA().isEqual(key)) {
                r = t;
            }
        }
        if (r != null) {
            return ring.remove(r);
        } else {
            return false;
        }
    }

    public int size() {
        return ring.size();
    }

    public Id get(int i) {
        try {
            return ring.get(i).getA();
        } catch (Exception e) {
            return new DoubleId(Double.NaN);
        }
    }
}
